﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using ContractManager.BLL.Business;
using ContractManager.Common.Class;
using ContractManager.Common.FormBase;
using System.Windows.Forms;
using ContractManager.Entity;
using ContractManager.Lists.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraGrid.Views.Grid;

namespace ContractManager.Lists.Contracts
{
    public partial class FrmContractsDetail : XtraFormBase
    {
        #region "Private Variable"
        
        public bool SaveClose;
        public bool SaveNew;
        public bool OnlyView;
        public int MasterId;

        public int InvID;

        private readonly BackgroundWorker _loadworker = new BackgroundWorker();

        public List<Citys> LstCity =  new List<Citys>();
        public List<InsuranceType> LstInsuranceType = new List<InsuranceType>();
        public List<Categories> LstCategory = new List<Categories>();
        public List<Resources> LstResources = new List<Resources>();
        public List<Capitals> LstCapitals = new List<Capitals>();
        public List<MemberBranch> LstMemberBranch = new List<MemberBranch>();
        public List<ContractType> LstContractType = new List<ContractType>();
        public List<Investors> LstInvestors = new List<Investors>();
        public List<Employees> LstEmployees = new List<Employees>();
        public DataTable DtContracts;
        public List<ContractStatus> LstContractStatus = new List<ContractStatus>();
        public List<WorkType> LstWorkType = new List<WorkType>(); 
        #endregion

        #region "Form Construction"
        public FrmContractsDetail()
        {
            InitializeComponent();
            ClsVariable.DoubleBuffer(this);
            _loadworker.DoWork += loadworker_DoWork;
            _loadworker.RunWorkerCompleted += loadworker_RunWorkerCompleted;
        }
        #endregion

        #region "Private Method"

        private void BlankForm()
        {
            ResetControls();
            grdDetail.DataSource = ClsContracts.ListDetail(0);   
        }

        public void GetData()
        {
            if (!_loadworker.IsBusy)
            {
                _loadworker.RunWorkerAsync();
                ClsVariable.SetWaitDialogCaption(string.Format("Nạp danh sách {0}...", Text));
            }
        }

        private void LoadLookupData()
        {
            txtInsTypId.Properties.DataSource = LstInsuranceType;
            txtInsTypId.Properties.DisplayMember = "InsTypName";
            txtInsTypId.Properties.ValueMember = "InsTypId";
         
            txtCatId.Properties.DataSource = LstCategory;
            txtCatId.Properties.DisplayMember = "CatName";
            txtCatId.Properties.ValueMember = "CatId";

            txtResId.Properties.DataSource = LstResources;
            txtResId.Properties.DisplayMember = "ResName";
            txtResId.Properties.ValueMember = "ResId";

            txtCapId.Properties.DataSource = LstCapitals;
            txtCapId.Properties.DisplayMember = "CapName";
            txtCapId.Properties.ValueMember = "CapId";

            txtEmpId.Properties.DataSource = LstEmployees;
            txtEmpId.Properties.DisplayMember = "FullName";
            txtEmpId.Properties.ValueMember = "ID";

            txtMbID.Properties.DataSource = LstMemberBranch;
            txtMbID.Properties.DisplayMember = "MbName";
            txtMbID.Properties.ValueMember = "MbID";

            txtConTypId.Properties.DataSource = LstContractType;
            txtConTypId.Properties.DisplayMember = "ConTypName";
            txtConTypId.Properties.ValueMember = "ConTypId";


            txtConLocation.Properties.DataSource = LstCity;
            txtConLocation.Properties.DisplayMember = "CityName";
            txtConLocation.Properties.ValueMember = "CityName";

            txtConPartA.Properties.DataSource = LstInvestors;
            txtConPartA.Properties.DisplayMember = "InvName";
            txtConPartA.Properties.ValueMember = "InvID";

            InvestorSearchLookUpEdit.DataSource = LstInvestors;
            InvestorSearchLookUpEdit.DisplayMember = "InvName";
            InvestorSearchLookUpEdit.ValueMember = "InvID";

            branchSearchLookUpEdit.DataSource = LstMemberBranch;
            branchSearchLookUpEdit.DisplayMember = "MbName";
            branchSearchLookUpEdit.ValueMember = "MbID";

            workSearchLookUpEdit.DataSource = LstWorkType;
            workSearchLookUpEdit.DisplayMember = "WorkName";
            workSearchLookUpEdit.ValueMember = "WorkId";

            ContractStatusSearchLookUpEdit.DataSource = LstContractStatus;
            ContractStatusSearchLookUpEdit.DisplayMember = "ConStaName";
            ContractStatusSearchLookUpEdit.ValueMember = "ConStaID";

            empSearchLookUpEdit.DataSource = LstEmployees;
            empSearchLookUpEdit.DisplayMember = "FullName";
            empSearchLookUpEdit.ValueMember = "FullName";

            if (MasterId > 0) GetDetail();
            if (InvID > 0) txtConPartA.EditValue = InvID;
        }

        private void GetDetail()
        {
            var detail = ClsContracts.SelectByPk(MasterId);
            if (detail != null)
            {
                txtConNo.EditValue = String.Format("{0}",detail.ConNo);
                txtConDate.EditValue = detail.ConDate;
                txtConPartNo.EditValue = detail.ConPartNo;
                txtConName.EditValue = detail.ConName;
                txtInsTypId.EditValue = detail.InsTypId;
                
                txtConLocation.EditValue = detail.ConLocation;
                txtResId.EditValue = detail.ResId;
                txtCapId.EditValue = detail.CapId;
                txtEmpId.EditValue = detail.EmpId;
                txtMbID.EditValue = detail.MbID;
                txtConTypId.EditValue = detail.ConTypId;
                if (detail.ConNo2 != null)
                {
                    var item = ClsContracts.SelectByPk(Convert.ToInt32(detail.ConNo2));
                    if (item != null) txtConNo2.EditValue = item.ConNo;
                }
                
                txtConName2.EditValue = String.Format("{0}", detail.ConName2);
                txtConDescription.EditValue = String.Format("{0}", detail.ConDescription);
                txtConPartA.EditValue = detail.ConPartA;
                txtConPartAPeople.EditValue = String.Format("{0}", detail.ConPartAPeople);
                txtConPartPostion.EditValue = String.Format("{0}", detail.ConPartPostion);
                txtConPartAddress.EditValue = String.Format("{0}", detail.ConPartAddress);
                txtConPartPhone.EditValue = String.Format("{0}", detail.ConPartPhone);
                txtConPartAccountNo.EditValue = String.Format("{0}", detail.ConPartAccountNo);
                txtConPartTaxCode.EditValue = String.Format("{0}", detail.ConPartTaxCode);
                txtConPartFax.EditValue = String.Format("{0}", detail.ConPartFax);
                txtConAmount.EditValue = detail.ConAmount;
                txtConSetAmount.EditValue = detail.ConSetAmount;
                txtConSentDate.EditValue = detail.ConSentDate;
                txtConReceiptDate.EditValue = detail.ConReceiptDate;
                txtConBusinessLicense.EditValue = String.Format("{0}", detail.ConBusinessLicense);
                txtCustomField1.EditValue = String.Format("{0}", detail.CustomField1);
                txtCustomField2.EditValue = String.Format("{0}", detail.CustomField2);
                txtCustomField3.EditValue = String.Format("{0}", detail.CustomField3);
                txtCustomField4.EditValue = String.Format("{0}", detail.CustomField4);
                txtCustomField5.EditValue = String.Format("{0}", detail.CustomField5);
                txtCustomField6.EditValue = String.Format("{0}", detail.CustomField6);
                txtCustomField7.EditValue = String.Format("{0}", detail.CustomField7);
                txtCustomField8.EditValue = String.Format("{0}", detail.CustomField8);
                txtCustomField9.EditValue = String.Format("{0}", detail.CustomField9);
                txtCustomField10.EditValue = String.Format("{0}", detail.CustomField10);
                txtConDateAccount.EditValue = detail.ConDateAccount;//Ngày quyết toán
                txtConDateDisposal.EditValue = detail.ConDateDisposal;//Ngày thanh lý
                txtCatId.EditValue = detail.CatId;
                txtCatId.SetEditValue(detail.CatId);
                grdDetail.DataSource = ClsContracts.ListDetail(MasterId);

                if (this.LstLockDate.Contains(Convert.ToDateTime(detail.ConReceiptDate).Date))
                {
                    OnlyView = true;
                    btnSaveNew.Enabled = !OnlyView;
                    btnSave.Enabled = !OnlyView;
                    btnSaveClose.Enabled = !OnlyView;
                    btnDelete.Enabled = !OnlyView && this.AllowDelete;
                    btnDesign.Enabled = !OnlyView;
                }
            } 
  

        }

        private void DoSave()
        {
            grdDetail.EmbeddedNavigator.Buttons.DoClick(grdDetail.EmbeddedNavigator.Buttons.EndEdit);

            #region "Variable"
            
            var dtSource = (DataTable)grdDetail.DataSource;

            #endregion

            #region "Check Condition"
            //if (!FormIsNotValidate)
            //{
            //    if (!dxValidationProvider.Validate())
            //    {
            //        XtraMessageBox.Show(
            //                    "Vui lòng nhập đầy đủ thông tin trước khi lưu",
            //                    "Thông báo",
            //                    MessageBoxButtons.OK,
            //                    MessageBoxIcon.Error);
            //        txtCode.SelectAll();
            //        txtCode.Focus();
            //        return;
            //    }
            //}
            if (txtConReceiptDate.EditValue != null)
            {
                if (LstLockDate.Contains(txtConReceiptDate.DateTime.Date))
                {
                    XtraMessageBox.Show(
                                    "Ngày chứng từ đã bị khoá sổ. Vui lòng nhập ngày khác",
                                    "Thông báo",
                                    MessageBoxButtons.OK,
                                    MessageBoxIcon.Error);
                    txtConReceiptDate.SelectAll();
                    txtConReceiptDate.Focus();
                    return;
                }
            }
            

            if (dtSource.Rows.Count == 0)
            {
                XtraMessageBox.Show(
                            "Số lượng công việc trong hợp đồng phải >0.",
                            "Thông báo",
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Error);
                txtConNo.SelectAll();
                txtConNo.Focus();
                return;
            }
            #endregion
            

            Entity.Contracts item = MasterId <= 0 ? new Entity.Contracts() : ClsContracts.SelectByPk(MasterId);
            item.ConNo = String.Format("{0}", txtConNo.EditValue);
            item.ConDate = txtConDate.DateTime;
            item.ConPartNo = String.Format("{0}", txtConPartNo.EditValue);
            item.ConName = String.Format("{0}", txtConName.EditValue);
            if (txtInsTypId.EditValue!=null) item.InsTypId = Convert.ToInt32(txtInsTypId.EditValue);
            item.InsTypName = String.Format("{0}", txtInsTypId.Text);
            item.CatId = txtCatId.EditValue != null ? String.Format("{0}", txtCatId.EditValue) : "";
            item.CatName = String.Format("{0}", txtCatId.Text);
            item.ConLocation = String.Format("{0}", txtConLocation.EditValue);
            if (txtResId.EditValue != null) item.ResId = Convert.ToInt32(txtResId.EditValue);
            item.ResName = String.Format("{0}", txtResId.Text);
            if (txtCapId.EditValue != null) item.CapId = Convert.ToInt32(txtCapId.EditValue);
            item.CapName = String.Format("{0}", txtCapId.Text);
            if (txtEmpId.EditValue != null) item.EmpId = Convert.ToInt32(txtEmpId.EditValue);
            item.EmpName = String.Format("{0}", txtEmpId.Text);
            if (txtMbID.EditValue != null) item.MbID = Convert.ToInt32(txtMbID.EditValue);
            item.MbName = String.Format("{0}", txtMbID.Text);
            if (txtConTypId.EditValue != null) item.ConTypId = Convert.ToInt32(txtConTypId.EditValue);
            item.ConTypName = String.Format("{0}", txtConTypId.Text);
            if (txtConNo2.Tag != null) item.ConNo2 = Convert.ToInt32(txtConNo2.Tag);
            item.ConParentNo = String.Format("{0}", txtConNo2.Text);
            item.ConName2 = String.Format("{0}", txtConName2.EditValue);
            item.ConDescription = String.Format("{0}", txtConDescription.EditValue);
            if (txtConPartA.EditValue != null) item.ConPartA = Convert.ToInt32(txtConPartA.EditValue);
            item.ConPartAName = String.Format("{0}", txtConPartA.Text);

            item.ConPartAPeople = String.Format("{0}", txtConPartAPeople.EditValue);
            item.ConPartPostion = String.Format("{0}", txtConPartPostion.EditValue);
            item.ConPartAddress = String.Format("{0}", txtConPartAddress.EditValue);
            item.ConPartPhone = String.Format("{0}", txtConPartPhone.EditValue);
            item.ConPartAccountNo = String.Format("{0}", txtConPartAccountNo.EditValue);
            item.ConPartTaxCode = String.Format("{0}", txtConPartTaxCode.EditValue);
            item.ConPartFax = String.Format("{0}", txtConPartFax.EditValue);
            item.ConAmount = Convert.ToDouble(txtConAmount.Value);
            item.ConSetAmount = Convert.ToDouble(txtConSetAmount.Value);
            //item.ConSentDate = txtConSentDate.DateTime;
            if (txtConSentDate.EditValue != null) item.ConSentDate = txtConSentDate.DateTime;
            if (txtConReceiptDate.EditValue != null) item.ConReceiptDate = txtConReceiptDate.DateTime;
            if (txtConDateAccount.EditValue != null) item.ConDateAccount = txtConDateAccount.DateTime;
            if (txtConDateDisposal.EditValue != null) item.ConDateDisposal = txtConDateDisposal.DateTime;

            item.ConBusinessLicense = String.Format("{0}", txtConBusinessLicense.EditValue);
            item.CustomField1 = String.Format("{0}", txtCustomField1.EditValue);
            item.CustomField2 = String.Format("{0}", txtCustomField2.EditValue);
            item.CustomField3 = String.Format("{0}", txtCustomField3.EditValue);
            item.CustomField4 = String.Format("{0}", txtCustomField4.EditValue);
            item.CustomField5 = String.Format("{0}", txtCustomField5.EditValue);
            item.CustomField6 = String.Format("{0}", txtCustomField6.EditValue);
            item.CustomField7 = String.Format("{0}", txtCustomField7.EditValue);
            item.CustomField8 = String.Format("{0}", txtCustomField8.EditValue);
            item.CustomField9 = String.Format("{0}", txtCustomField9.EditValue);
            item.CustomField10 = String.Format("{0}", txtCustomField10.EditValue);

            item.FormId = FormNo;
            item.VoucherCate = VoucherCate;

            item.ListAdd = GetListAdd(dtSource.GetChanges(DataRowState.Added));
            item.ListUpdate = GetListUpdate(dtSource.GetChanges(DataRowState.Modified));
            item.ListDelete = GetListDelete(dtSource.GetChanges(DataRowState.Deleted));
            item.ListCategory = GetListCategory(item.CatId);
            try
            {
                this.Cursor = System.Windows.Forms.Cursors.WaitCursor;
                if (MasterId > 0)
                {
                    item.UpdateBy = ClsVariable.EmployeeId;
                    item.UpdateByName = ClsVariable.FullName;
                    item.UpdateDate = DateTime.Now;
                    ClsContracts.Update(item); 
                }
                else
                {
                    item.CreateBy = ClsVariable.EmployeeId;
                    item.CreateByName = ClsVariable.FullName;
                    item.CreateDate = DateTime.Now;
                    ClsContracts.Insert(item);
                    MasterId = item.ConId;
                }
                if (this.FormSysBillStyleIdExport>0) ClsContracts.SynchContracts(MasterId);
                dtSource.AcceptChanges();
                grdDetail.DataSource = ClsContracts.ListDetail(MasterId);
                if (SaveNew)
                {
                    MasterId = 0;
                    BlankForm();
                    txtConNo.Focus();
                }
                else if (SaveClose)
                {
                    Close();
                }
                this.Cursor = System.Windows.Forms.Cursors.Default;
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(
                    String.Format("Có lỗi xảy ra trong quá trình cập nhật dữ liệu. {0}", ex.Message),
                    "Thông báo",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
            }
        }

        private void DoDelete()
        {
            if (MasterId <= 0) return;
            
            try
            {
                if (
                        XtraMessageBox.Show(
                                        "Bạn có muốn xóa bản ghi này không?",
                                        "Thông báo",
                                        MessageBoxButtons.YesNo,
                                        MessageBoxIcon.Question) == DialogResult.No) return;
                ClsContracts.DeleteByPk(MasterId);
                Close();
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(
                       "Có lỗi xảy ra trong quá trình xóa dữ liệu. " + ex.Message,
                       "Thông báo",
                       MessageBoxButtons.OK,
                       MessageBoxIcon.Error);
            }
        }

        private List<ContractDetails> GetListAdd(DataTable dataTable)
        {
            List<ContractDetails> list = new List<ContractDetails>();
            if (dataTable != null && dataTable.Rows.Count > 0)
            {
                dataTable.BeginLoadData();
                foreach (DataRow row in dataTable.Rows)
                {
                    ContractDetails item = new ContractDetails();
                    item.ConDetId = 0;
                    item.ConDetContent = String.Format("{0}", row["ConDetContent"]);
                    item.ConDetAmount = row["ConDetAmount"] == DBNull.Value ? 0 : Convert.ToDouble(row["ConDetAmount"]);
                    item.ConDetSetAmount = row["ConDetSetAmount"] == DBNull.Value ? 0 : Convert.ToDouble(row["ConDetSetAmount"]);
                    if (!row.IsNull("ConDetStartDate") && row["ConDetStartDate"] != DBNull.Value)
                    {
                        item.ConDetStartDate = Convert.ToDateTime(row["ConDetStartDate"]);
                    }
                    if (!row.IsNull("ConDetEndDate") && row["ConDetEndDate"] != DBNull.Value)
                    {
                        item.ConDetEndDate = Convert.ToDateTime(row["ConDetEndDate"]);
                    }
                    if (!row.IsNull("ConDetPlanEndDate") && row["ConDetPlanEndDate"] != DBNull.Value)
                    {
                        item.ConDetEndDate = Convert.ToDateTime(row["ConDetPlanEndDate"]);
                    }
                    item.ConDetStatus = String.Format("{0}", row["ConDetStatus"]);
                    item.ConDetDecisionNo = String.Format("{0}", row["ConDetDecisionNo"]);
                    if (!row.IsNull("ConDetDeliveryDate") && row["ConDetDeliveryDate"] != DBNull.Value)
                    {
                        item.ConDetEndDate = Convert.ToDateTime(row["ConDetDeliveryDate"]);
                    }
                    if (!row.IsNull("MbID") && row["MbID"] != DBNull.Value)
                    {
                        item.MbID = Convert.ToInt32(row["MbID"]);
                    }

                    item.ConDetAllocationDecision = String.Format("{0}", row["ConDetAllocationDecision"]);
                    item.ConDetCtManager = String.Format("{0}", row["ConDetCtManager"]);
                    item.ConDetLeader = String.Format("{0}", row["ConDetLeader"]);
                    if (!row.IsNull("WorkId") && row["WorkId"] != DBNull.Value)
                    {
                        item.WorkId = Convert.ToInt32(row["WorkId"]); 
                    }

                    item.ConDetVatRate = row["ConDetVatRate"] == DBNull.Value ? 0 : Convert.ToDouble(row["ConDetVatRate"]);
                    item.ConDetVatAmount = row["ConDetVatAmount"] == DBNull.Value ? 0 : Convert.ToDouble(row["ConDetVatAmount"]);

                    item.ConDetInsRate = row["ConDetInsRate"] == DBNull.Value ? 0 : Convert.ToDouble(row["ConDetInsRate"]);
                    item.ConDetInsAmount = row["ConDetInsAmount"] == DBNull.Value ? 0 : Convert.ToDouble(row["ConDetInsAmount"]);
                    item.ConDetInsAfterAmount = row["ConDetInsAfterAmount"] == DBNull.Value ? 0 : Convert.ToDouble(row["ConDetInsAfterAmount"]);
                    item.ConDetExcRate = row["ConDetExcRate"] == DBNull.Value ? 0 : Convert.ToDouble(row["ConDetExcRate"]);
                    item.ConDetExcAmount = row["ConDetExcAmount"] == DBNull.Value ? 0 : Convert.ToDouble(row["ConDetExcAmount"]);
                    item.ConDetTransAmount = row["ConDetTransAmount"] == DBNull.Value ? 0 : Convert.ToDouble(row["ConDetTransAmount"]);
                    item.ConDetBalanceAmount = row["ConDetBalanceAmount"] == DBNull.Value ? 0 : Convert.ToDouble(row["ConDetBalanceAmount"]);
                    item.ConDetVccAmount = row["ConDetVccAmount"] == DBNull.Value ? 0 : Convert.ToDouble(row["ConDetVccAmount"]);
                    item.ConDetNumDay = row["ConDetNumDay"] == DBNull.Value ? 0 : Convert.ToInt32(row["ConDetNumDay"]);

                    if (!row.IsNull("ConDetDatePayment") && row["ConDetDatePayment"] != DBNull.Value)
                    {
                        item.ConDetDatePayment = Convert.ToDateTime(row["ConDetDatePayment"]);
                    }

                    if (!row.IsNull("ConDetDateAcceptProduct") && row["ConDetDateAcceptProduct"] != DBNull.Value)
                    {
                        item.ConDetDateAcceptProduct = Convert.ToDateTime(row["ConDetDateAcceptProduct"]);
                    }

                    if (!row.IsNull("ConDetDateAcceptValue") && row["ConDetDateAcceptValue"] != DBNull.Value)
                    {
                        item.ConDetDateAcceptValue = Convert.ToDateTime(row["ConDetDateAcceptValue"]);
                    }
                    item.ConDetNameBSide = String.Format("{0}", row["ConDetNameBSide"]);

                    item.CustomField1 = String.Format("{0}", row["CustomField1"]);
                    item.CustomField2 = String.Format("{0}", row["CustomField2"]);
                    item.CustomField3 = String.Format("{0}", row["CustomField3"]);
                    item.CustomField4 = String.Format("{0}", row["CustomField4"]);
                    item.CustomField5 = String.Format("{0}", row["CustomField5"]);

                    list.Add(item);
                    
                }
                dataTable.EndLoadData();
            }
            return list;
        }

        private List<ContractDetails> GetListUpdate(DataTable dataTable)
        {
            List<ContractDetails> list = new List<ContractDetails>();
            if (dataTable != null && dataTable.Rows.Count > 0)
            {
                dataTable.BeginLoadData();
                foreach (DataRow row in dataTable.Rows)
                {
                    ContractDetails item = new ContractDetails();
                    item.ConDetId = Convert.ToInt32(row["ConDetId"]);
                    item.ConDetContent = String.Format("{0}", row["ConDetContent"]);
                    item.ConDetAmount = row["ConDetAmount"] == DBNull.Value ? 0 : Convert.ToDouble(row["ConDetAmount"]);
                    item.ConDetSetAmount = row["ConDetSetAmount"] == DBNull.Value ? 0 : Convert.ToDouble(row["ConDetSetAmount"]);
                    if (!row.IsNull("ConDetStartDate") && row["ConDetStartDate"] != DBNull.Value)
                    {
                        item.ConDetStartDate = Convert.ToDateTime(row["ConDetStartDate"]);
                    }
                    if (!row.IsNull("ConDetEndDate") && row["ConDetEndDate"] != DBNull.Value)
                    {
                        item.ConDetEndDate = Convert.ToDateTime(row["ConDetEndDate"]);
                    }
                    if (!row.IsNull("ConDetPlanEndDate") && row["ConDetPlanEndDate"] != DBNull.Value)
                    {
                        item.ConDetEndDate = Convert.ToDateTime(row["ConDetPlanEndDate"]);
                    }
                    item.ConDetStatus = String.Format("{0}", row["ConDetStatus"]);
                    item.ConDetDecisionNo = String.Format("{0}", row["ConDetDecisionNo"]);
                    if (!row.IsNull("ConDetDeliveryDate") && row["ConDetDeliveryDate"] != DBNull.Value)
                    {
                        item.ConDetEndDate = Convert.ToDateTime(row["ConDetDeliveryDate"]);
                    }
                    if (!row.IsNull("MbID") && row["MbID"] != DBNull.Value)
                    {
                        item.MbID = Convert.ToInt32(row["MbID"]);
                    }
                    item.ConDetAllocationDecision = String.Format("{0}", row["ConDetAllocationDecision"]);
                    item.ConDetCtManager = String.Format("{0}", row["ConDetCtManager"]);
                    item.ConDetLeader = String.Format("{0}", row["ConDetLeader"]);
                    if (!row.IsNull("WorkId") && row["WorkId"] != DBNull.Value)
                    {
                        item.WorkId = Convert.ToInt32(row["WorkId"]);
                    }
                    item.ConDetVatRate = row["ConDetVatRate"] == DBNull.Value ? 0 : Convert.ToDouble(row["ConDetVatRate"]);
                    item.ConDetVatAmount = row["ConDetVatAmount"] == DBNull.Value ? 0 : Convert.ToDouble(row["ConDetVatAmount"]);

                    item.ConDetInsRate = row["ConDetInsRate"] == DBNull.Value ? 0 : Convert.ToDouble(row["ConDetInsRate"]);
                    item.ConDetInsAmount = row["ConDetInsAmount"] == DBNull.Value ? 0 : Convert.ToDouble(row["ConDetInsAmount"]);
                    item.ConDetInsAfterAmount = row["ConDetInsAfterAmount"] == DBNull.Value ? 0 : Convert.ToDouble(row["ConDetInsAfterAmount"]);
                    item.ConDetExcRate = row["ConDetExcRate"] == DBNull.Value ? 0 : Convert.ToDouble(row["ConDetExcRate"]);
                    item.ConDetExcAmount = row["ConDetExcAmount"] == DBNull.Value ? 0 : Convert.ToDouble(row["ConDetExcAmount"]);
                    item.ConDetTransAmount = row["ConDetTransAmount"] == DBNull.Value ? 0 : Convert.ToDouble(row["ConDetTransAmount"]);
                    item.ConDetBalanceAmount = row["ConDetBalanceAmount"] == DBNull.Value ? 0 : Convert.ToDouble(row["ConDetBalanceAmount"]);
                    item.ConDetVccAmount = row["ConDetVccAmount"] == DBNull.Value ? 0 : Convert.ToDouble(row["ConDetVccAmount"]);
                    item.ConDetNumDay = row["ConDetNumDay"] == DBNull.Value ? 0 : Convert.ToInt32(row["ConDetNumDay"]);

                    if (!row.IsNull("ConDetDatePayment") && row["ConDetDatePayment"] != DBNull.Value)
                    {
                        item.ConDetDatePayment = Convert.ToDateTime(row["ConDetDatePayment"]);
                    }

                    if (!row.IsNull("ConDetDateAcceptProduct") && row["ConDetDateAcceptProduct"] != DBNull.Value)
                    {
                        item.ConDetDateAcceptProduct = Convert.ToDateTime(row["ConDetDateAcceptProduct"]);
                    }

                    if (!row.IsNull("ConDetDateAcceptValue") && row["ConDetDateAcceptValue"] != DBNull.Value)
                    {
                        item.ConDetDateAcceptValue = Convert.ToDateTime(row["ConDetDateAcceptValue"]);
                    }
                    item.ConDetNameBSide = String.Format("{0}", row["ConDetNameBSide"]);

                    item.CustomField1 = String.Format("{0}", row["CustomField1"]);
                    item.CustomField2 = String.Format("{0}", row["CustomField2"]);
                    item.CustomField3 = String.Format("{0}", row["CustomField3"]);
                    item.CustomField4 = String.Format("{0}", row["CustomField4"]);
                    item.CustomField5 = String.Format("{0}", row["CustomField5"]);

                    list.Add(item);

                }
                dataTable.EndLoadData();
            }
            return list;
        }

        private List<ContractDetails> GetListDelete(DataTable dataTable)
        {
            List<ContractDetails> list = new List<ContractDetails>();
            if (dataTable != null && dataTable.Rows.Count > 0)
            {
                dataTable.BeginLoadData();
                foreach (DataRow row in dataTable.Rows)
                {
                    ContractDetails item = new ContractDetails();
                    item.ConDetId = Convert.ToInt32(row["ConDetId",DataRowVersion.Original]);
                    list.Add(item);

                }
                dataTable.EndLoadData();
            }
            return list;
        }

        private List<ContractCategory> GetListCategory(String categoryId)
        {
            List<ContractCategory> list = new List<ContractCategory>();
            string[] arr = categoryId.Split(',');
            
            foreach (string row in arr)
            {
                if (row.Trim().Length > 0)
                {
                    ContractCategory item = new ContractCategory();
                    item.ConId = 0;
                    item.CatId = Convert.ToInt32(row.Trim());
                    list.Add(item);
                }
                
            }
            return list;
        }

        #endregion

        #region "Background Worker"

        private void loadworker_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                LstInsuranceType = ClsInsuranceType.SelectAll();
                LstCategory = ClsCategories.SelectAll();
                LstResources = ClsResources.SelectAll();
                LstCapitals = ClsCapitals.SelectAll();
                LstEmployees = ClsEmployees.SelectAll();
                LstMemberBranch = ClsMemberBranch.SelectAll();
                LstContractType = ClsContractType.SelectAll();
               
                LstCity = ClsCitys.SelectAll();
                LstInvestors = ClsInvestors.SelectAll();
                LstWorkType = ClsWorkType.SelectAll();
                LstContractStatus = ClsContractStatus.SelectAll();
                e.Result = LstInsuranceType;
            }
            catch (Exception)
            {
                e.Cancel = true;
            }
        }

        private void loadworker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            Action a = LoadLookupData;
            txtInsTypId.Invoke(a);
            ClsVariable.SetWaitDialogCaption(string.Format("Danh sách {0} đã được nạp", Text));
        }
        #endregion

        #region "Form Event"
        private void FrmContractsDetailLoad(object sender, EventArgs e)
        {
            BlankForm();
            GetData();
            btnSaveNew.Enabled = !OnlyView;
            btnSave.Enabled = !OnlyView;
            btnSaveClose.Enabled = !OnlyView;
            btnDelete.Enabled = !OnlyView && this.AllowDelete;
            
            btnDesign.Enabled = !OnlyView;
            if (!String.IsNullOrEmpty(FormXtraLayoutTemplate))
            {
                var fileLayout = ClsVariable.GetRestoreLayoutFullPath(FormXtraLayoutTemplate);
                layoutControl.RestoreLayoutFromXml(fileLayout);
            }
            if (String.IsNullOrEmpty(FormXtraGridLayoutTemplate)) return;
            grdDetail.ForceInitialize();
            var filePath = ClsVariable.GetRestoreLayoutFullPath(FormXtraGridLayoutTemplate);
            grvDetail.RestoreLayoutFromXml(filePath, DevExpress.Utils.OptionsLayoutBase.FullLayout);
        }
        #endregion

        #region "Toolbar Event"
        private void TbMenuItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            switch (e.Item.Name)
            {
                case "btnSave":
                    DoSave();
                    break;
                case "btnSaveNew"://Lưu và thêm mới
                    SaveNew = true;
                    DoSave();
                    break;
                case "btnSaveClose"://Lưu và đóng
                    SaveClose = true;
                    DoSave();
                    break;
                case "btnDelete":
                    DoDelete();
                    break;
                case "btnDesign":
                    ClsVariable.ShowDesignXtraGrid(grdDetail);
                    break;
                case "btnRefresh"://Nạp lại danh mục
                    if (txtConPartA.EditValue != null) InvID = Convert.ToInt32(txtConPartA.EditValue);
                    GetData();
                    break;
                case "btnHistory"://History
                    break;
                case "btnClose":
                    Close();
                    break;
            }
        }
        #endregion

        #region "Lookup Edit"
        private void txtConPartA_EditValueChanged(object sender, EventArgs e)
        {
            if (txtConPartA.EditValue != null)
            {
                var item = ClsInvestors.SelectByPk(Convert.ToInt32(txtConPartA.EditValue));
                //dai dien ben A
                txtConPartAPeople.EditValue = String.Format("{0}", item.InvRepresentative);
                txtConPartPostion.EditValue = String.Format("{0}", item.InvPosition);
                txtConPartAddress.EditValue = String.Format("{0}", item.InvAddress);
                txtConPartPhone.EditValue = String.Format("{0}", item.InvPhone);
                txtConPartAccountNo.EditValue = String.Format("{0}", item.InvBankAccount);
                txtConPartTaxCode.EditValue = String.Format("{0}", item.InvTaxCode);
                txtConPartFax.EditValue = String.Format("{0}", item.InvFax);
                txtConBusinessLicense.EditValue = String.Format("{0}", item.InvBusinessLicense);
            }
        }

        private void txtInsTypId_Properties_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            switch (e.Button.Caption)
            {
                case "btnAdd":
                    var item = ClsForms.SelectByFormClass("ContractManager.Lists.Forms.FrmInsuranceType");
                    if (item == null) return;
                    var frm = new FrmInsuranceTypeDetail
                    {
                        MasterId = 0,
                        AsSysBillStyleId = Convert.ToInt32(item.Form_SysBillStyleId),
                        AsSysMyCoYearId = ClsVariable.AsSysMyCoYearId,
                        AsPerPersonId = ClsVariable.EmployeeId,
                        FormNo = item.FormNo,
                        SaveFormMaster = true,
                        FormSysBillStyleIdExport = Convert.ToInt32(item.Form_SysBillStyleIdExport),
                        FormXtraLayoutTemplate = item.Form_XtraLayoutTemplate,
                        FormXtraGridLayoutTemplate = item.Form_XtraGridLayoutTemplate,
                        FormReportLayoutTemplate = item.Form_ReportLayoutTemplate,
                        FormDetailVatGridLayout = item.Form_DetailVatGridLayout,
                        VoucherCate = Convert.ToInt32(item.VoucherCate),
                        IsPrintAfterSave = Convert.ToBoolean(item.Form_IsPrintAfterSave),
                        FormAccountDefault = Convert.ToInt32(item.FormAccountDefault),
                        FormIsNotValidate = Convert.ToBoolean(item.FormIsNotValidate),
                        Text = String.Format("Thông tin {0}", item.Form_Name),

                        MdiParent = this.MdiParent,
                        WindowState = FormWindowState.Maximized
                    };
                    frm.Closed += FrmOnClosed;
                    frm.Show();
                   
                    break;
            }
        }

        private void txtCatId_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            switch (e.Button.Caption)
            {
                case "btnAdd":
                    var item = ClsForms.SelectByFormClass("ContractManager.Lists.Forms.FrmCategory");
                    if (item == null) return;
                    var frm = new FrmCategoryDetail
                    {
                        MasterId = 0,
                        AsSysBillStyleId = Convert.ToInt32(item.Form_SysBillStyleId),
                        AsSysMyCoYearId = ClsVariable.AsSysMyCoYearId,
                        AsPerPersonId = ClsVariable.EmployeeId,
                        FormNo = item.FormNo,
                        SaveFormMaster = true,
                        FormSysBillStyleIdExport = Convert.ToInt32(item.Form_SysBillStyleIdExport),
                        FormXtraLayoutTemplate = item.Form_XtraLayoutTemplate,
                        FormXtraGridLayoutTemplate = item.Form_XtraGridLayoutTemplate,
                        FormReportLayoutTemplate = item.Form_ReportLayoutTemplate,
                        FormDetailVatGridLayout = item.Form_DetailVatGridLayout,
                        VoucherCate = Convert.ToInt32(item.VoucherCate),
                        IsPrintAfterSave = Convert.ToBoolean(item.Form_IsPrintAfterSave),
                        FormAccountDefault = Convert.ToInt32(item.FormAccountDefault),
                        FormIsNotValidate = Convert.ToBoolean(item.FormIsNotValidate),
                        Text = String.Format("Thông tin {0}", item.Form_Name),

                        MdiParent = this.MdiParent,
                        WindowState = FormWindowState.Maximized
                    };
                    frm.Closed += FrmOnClosed;
                    frm.Show();
                    
                    break;
            }
            
        }

        private void txtConLocation_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            switch (e.Button.Caption)
            {
                case "btnAdd":
                    var item = ClsForms.SelectByFormClass("ContractManager.Lists.Forms.FrmCity");
                    if (item == null) return;
                    var frm = new FrmCityDetail
                    {
                        MasterId = 0,
                        AsSysBillStyleId = Convert.ToInt32(item.Form_SysBillStyleId),
                        AsSysMyCoYearId = ClsVariable.AsSysMyCoYearId,
                        AsPerPersonId = ClsVariable.EmployeeId,
                        FormNo = item.FormNo,
                        SaveFormMaster = true,
                        FormSysBillStyleIdExport = Convert.ToInt32(item.Form_SysBillStyleIdExport),
                        FormXtraLayoutTemplate = item.Form_XtraLayoutTemplate,
                        FormXtraGridLayoutTemplate = item.Form_XtraGridLayoutTemplate,
                        FormReportLayoutTemplate = item.Form_ReportLayoutTemplate,
                        FormDetailVatGridLayout = item.Form_DetailVatGridLayout,
                        VoucherCate = Convert.ToInt32(item.VoucherCate),
                        IsPrintAfterSave = Convert.ToBoolean(item.Form_IsPrintAfterSave),
                        FormAccountDefault = Convert.ToInt32(item.FormAccountDefault),
                        FormIsNotValidate = Convert.ToBoolean(item.FormIsNotValidate),
                        Text = String.Format("Thông tin {0}", item.Form_Name),

                        MdiParent = this.MdiParent,
                        WindowState = FormWindowState.Maximized
                    };
                    frm.Closed += FrmOnClosed;
                    frm.Show();

                    
                    break;
            }
            
        }


        private void txtResId_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            switch (e.Button.Caption)
            {
                case "btnAdd":
                    var item = ClsForms.SelectByFormClass("ContractManager.Lists.Forms.FrmResources");
                    if (item == null) return;
                    var frm = new FrmResourcesDetail
                    {
                        MasterId = 0,
                        AsSysBillStyleId = Convert.ToInt32(item.Form_SysBillStyleId),
                        AsSysMyCoYearId = ClsVariable.AsSysMyCoYearId,
                        AsPerPersonId = ClsVariable.EmployeeId,
                        FormNo = item.FormNo,
                        SaveFormMaster = true,
                        FormSysBillStyleIdExport = Convert.ToInt32(item.Form_SysBillStyleIdExport),
                        FormXtraLayoutTemplate = item.Form_XtraLayoutTemplate,
                        FormXtraGridLayoutTemplate = item.Form_XtraGridLayoutTemplate,
                        FormReportLayoutTemplate = item.Form_ReportLayoutTemplate,
                        FormDetailVatGridLayout = item.Form_DetailVatGridLayout,
                        VoucherCate = Convert.ToInt32(item.VoucherCate),
                        IsPrintAfterSave = Convert.ToBoolean(item.Form_IsPrintAfterSave),
                        FormAccountDefault = Convert.ToInt32(item.FormAccountDefault),
                        FormIsNotValidate = Convert.ToBoolean(item.FormIsNotValidate),
                        Text = String.Format("Thông tin {0}", item.Form_Name),

                        MdiParent = this.MdiParent,
                        WindowState = FormWindowState.Maximized
                    };
                    frm.Closed += FrmOnClosed;
                    frm.Show();
                    break;
            }
            
        }

        private void txtCapId_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            switch (e.Button.Caption)
            {
                case "btnAdd":
                    var item = ClsForms.SelectByFormClass("ContractManager.Lists.Forms.FrmCapitals");
                    if (item == null) return;
                    var frm = new FrmCapitalDetail
                    {
                        MasterId = 0,
                        AsSysBillStyleId = Convert.ToInt32(item.Form_SysBillStyleId),
                        AsSysMyCoYearId = ClsVariable.AsSysMyCoYearId,
                        AsPerPersonId = ClsVariable.EmployeeId,
                        FormNo = item.FormNo,
                        SaveFormMaster = true,
                        FormSysBillStyleIdExport = Convert.ToInt32(item.Form_SysBillStyleIdExport),
                        FormXtraLayoutTemplate = item.Form_XtraLayoutTemplate,
                        FormXtraGridLayoutTemplate = item.Form_XtraGridLayoutTemplate,
                        FormReportLayoutTemplate = item.Form_ReportLayoutTemplate,
                        FormDetailVatGridLayout = item.Form_DetailVatGridLayout,
                        VoucherCate = Convert.ToInt32(item.VoucherCate),
                        IsPrintAfterSave = Convert.ToBoolean(item.Form_IsPrintAfterSave),
                        FormAccountDefault = Convert.ToInt32(item.FormAccountDefault),
                        FormIsNotValidate = Convert.ToBoolean(item.FormIsNotValidate),
                        Text = String.Format("Thông tin {0}", item.Form_Name),

                        MdiParent = this.MdiParent,
                        WindowState = FormWindowState.Maximized
                    };
                    frm.Closed += FrmOnClosed;
                    frm.Show();
                    break;
            }
            
        }

        private void txtMbID_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            switch (e.Button.Caption)
            {
                case "btnAdd":
                    var item = ClsForms.SelectByFormClass("ContractManager.Lists.Forms.FrmMemberBranch");
                    if (item == null) return;
                    var frm = new FrmMemberBranchDetail
                    {
                        InvestorId = 0,
                        AsSysBillStyleId = Convert.ToInt32(item.Form_SysBillStyleId),
                        AsSysMyCoYearId = ClsVariable.AsSysMyCoYearId,
                        AsPerPersonId = ClsVariable.EmployeeId,
                        FormNo = item.FormNo,
                        SaveFormMaster = true,
                        FormSysBillStyleIdExport = Convert.ToInt32(item.Form_SysBillStyleIdExport),
                        FormXtraLayoutTemplate = item.Form_XtraLayoutTemplate,
                        FormXtraGridLayoutTemplate = item.Form_XtraGridLayoutTemplate,
                        FormReportLayoutTemplate = item.Form_ReportLayoutTemplate,
                        FormDetailVatGridLayout = item.Form_DetailVatGridLayout,
                        VoucherCate = Convert.ToInt32(item.VoucherCate),
                        IsPrintAfterSave = Convert.ToBoolean(item.Form_IsPrintAfterSave),
                        FormAccountDefault = Convert.ToInt32(item.FormAccountDefault),
                        FormIsNotValidate = Convert.ToBoolean(item.FormIsNotValidate),
                        Text = String.Format("Thông tin {0}", item.Form_Name),

                        MdiParent = this.MdiParent,
                        WindowState = FormWindowState.Maximized
                    };
                    frm.Closed += FrmOnClosed;
                    frm.Show();
                    break;
            }
            
        }

        private void txtConTypId_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            switch (e.Button.Caption)
            {
                case "btnAdd":
                    var item = ClsForms.SelectByFormClass("ContractManager.Lists.Forms.FrmContractType");
                    if (item == null) return;
                    var frm = new FrmContractTypeDetail
                    {
                        MasterId = 0,
                        AsSysBillStyleId = Convert.ToInt32(item.Form_SysBillStyleId),
                        AsSysMyCoYearId = ClsVariable.AsSysMyCoYearId,
                        AsPerPersonId = ClsVariable.EmployeeId,
                        FormNo = item.FormNo,
                        SaveFormMaster = true,
                        FormSysBillStyleIdExport = Convert.ToInt32(item.Form_SysBillStyleIdExport),
                        FormXtraLayoutTemplate = item.Form_XtraLayoutTemplate,
                        FormXtraGridLayoutTemplate = item.Form_XtraGridLayoutTemplate,
                        FormReportLayoutTemplate = item.Form_ReportLayoutTemplate,
                        FormDetailVatGridLayout = item.Form_DetailVatGridLayout,
                        VoucherCate = Convert.ToInt32(item.VoucherCate),
                        IsPrintAfterSave = Convert.ToBoolean(item.Form_IsPrintAfterSave),
                        FormAccountDefault = Convert.ToInt32(item.FormAccountDefault),
                        FormIsNotValidate = Convert.ToBoolean(item.FormIsNotValidate),
                        Text = String.Format("Thông tin {0}", item.Form_Name),

                        MdiParent = this.MdiParent,
                        WindowState = FormWindowState.Maximized
                    };
                    frm.Closed += FrmOnClosed;
                    frm.Show();
                    
                    break;
            }
            
        }

        private void txtConPartA_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            switch (e.Button.Caption)
            {
                case "btnAdd":
                    var item = ClsForms.SelectByFormClass("ContractManager.Lists.Forms.FrmInvestors");
                    if (item == null) return;
                    var frm = new FrmInvestorDetail
                    {
                        InvestorId = 0,
                        AsSysBillStyleId = Convert.ToInt32(item.Form_SysBillStyleId),
                        AsSysMyCoYearId = ClsVariable.AsSysMyCoYearId,
                        AsPerPersonId = ClsVariable.EmployeeId,
                        FormNo = item.FormNo,
                        SaveFormMaster = true,
                        FormSysBillStyleIdExport = Convert.ToInt32(item.Form_SysBillStyleIdExport),
                        FormXtraLayoutTemplate = item.Form_XtraLayoutTemplate,
                        FormXtraGridLayoutTemplate = item.Form_XtraGridLayoutTemplate,
                        FormReportLayoutTemplate = item.Form_ReportLayoutTemplate,
                        FormDetailVatGridLayout = item.Form_DetailVatGridLayout,
                        VoucherCate = Convert.ToInt32(item.VoucherCate),
                        IsPrintAfterSave = Convert.ToBoolean(item.Form_IsPrintAfterSave),
                        FormAccountDefault = Convert.ToInt32(item.FormAccountDefault),
                        FormIsNotValidate = Convert.ToBoolean(item.FormIsNotValidate),
                        Text = String.Format("Thông tin {0}", item.Form_Name),

                        MdiParent = this.MdiParent,
                        WindowState = FormWindowState.Maximized
                    };
                    frm.Closed += FrmOnClosed;
                    frm.Show();
                    break;
            }
            
        }

        private void FrmOnClosed(object sender, EventArgs eventArgs)
        {
            var frmInsTypeDetail = sender as FrmInsuranceTypeDetail;
            if (frmInsTypeDetail != null && frmInsTypeDetail.SaveClose)
            {
                if (frmInsTypeDetail.List != null)
                {
                    foreach (var lstItem in frmInsTypeDetail.List)
                    {
                        LstInsuranceType.Add(lstItem);
                        txtInsTypId.EditValue = lstItem.InsTypId;
                        txtInsTypId.Refresh();
                    }
                }
            }
            var frmCategoryDetail = sender as FrmCategoryDetail;
            if (frmCategoryDetail != null && frmCategoryDetail.SaveClose)
            {
                if (frmCategoryDetail.List != null)
                {
                    foreach (var lstItem in frmCategoryDetail.List)
                    {
                        LstCategory.Add(lstItem);
                        txtCatId.EditValue = lstItem.CatId;
                        txtCatId.Refresh();
                    }
                }
            }

            var frmCityDetail = sender as FrmCityDetail;
            if (frmCityDetail != null && frmCityDetail.SaveClose)
            {
                if (frmCityDetail.List != null)
                {
                    foreach (var lstItem in frmCityDetail.List)
                    {
                        LstCity.Add(lstItem);
                        txtConLocation.EditValue = lstItem.CityId;
                        txtConLocation.Refresh();
                    }
                }
            }

            var frmResourceDetail = sender as FrmResourcesDetail;
            if (frmResourceDetail != null && frmResourceDetail.SaveClose)
            {
                if (frmResourceDetail.List != null)
                {
                    foreach (var lstItem in frmResourceDetail.List)
                    {
                        LstResources.Add(lstItem);
                        txtResId.EditValue = lstItem.ResId;
                        txtResId.Refresh();
                    }
                }
            }

            var frmCapitalDetail = sender as FrmCapitalDetail;
            if (frmCapitalDetail != null && frmCapitalDetail.SaveClose)
            {
                if (frmCapitalDetail.List != null)
                {
                    foreach (var lstItem in frmCapitalDetail.List)
                    {
                        LstCapitals.Add(lstItem);
                        txtCapId.EditValue = lstItem.CapId;
                        txtCapId.Refresh();
                    }
                }
            }

            var frmMemberBranchDetail = sender as FrmMemberBranchDetail;
            if (frmMemberBranchDetail != null && frmMemberBranchDetail.SaveClose)
            {
                if (frmMemberBranchDetail.List != null)
                {
                    foreach (var lstItem in frmMemberBranchDetail.List)
                    {
                        LstMemberBranch.Add(lstItem);
                        txtMbID.EditValue = lstItem.MbID;
                        txtMbID.Refresh();
                    }
                }
            }

            var frmContractTypeDetail = sender as FrmContractTypeDetail;
            if (frmContractTypeDetail != null && frmContractTypeDetail.SaveClose)
            {
                if (frmContractTypeDetail.List != null)
                {
                    foreach (var lstItem in frmContractTypeDetail.List)
                    {
                        LstContractType.Add(lstItem);
                        txtConTypId.EditValue = lstItem.ConTypId;
                        txtConTypId.Refresh();
                    }
                }
            }

            var frmInvestorDetail = sender as FrmInvestorDetail;
            if (frmInvestorDetail != null && frmInvestorDetail.SaveClose)
            {
                if (frmInvestorDetail.List != null)
                {
                    foreach (var lstItem in frmInvestorDetail.List)
                    {
                        LstInvestors.Add(lstItem);
                        txtConPartA.EditValue = lstItem.InvID;
                        txtConPartA.Refresh();
                    }
                }
            }
        }

        #endregion

        #region "XtraGrid Event"
        private void grvDetail_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if (e.Value == null) return;
            var view = (GridView)sender;
            decimal dVatRate, dVatAmount, dInsRate, dInsAmount, dInsAfterAmount, dTranAmount, dBalanceAmount, dSetAmount;

            switch (e.Column.FieldName)
            {
                case "ConDetSetAmount":
                    if (e.Value != null && e.Value != DBNull.Value)
                    {
                        dSetAmount = Convert.ToDecimal(e.Value);
                        dVatRate = view.GetRowCellValue(e.RowHandle, "ConDetVatRate") == null
                            || view.GetRowCellValue(e.RowHandle, "ConDetVatRate") == DBNull.Value ? 0 :
                                        Convert.ToDecimal(view.GetRowCellValue(e.RowHandle, "ConDetVatRate"));
                        dVatAmount = Math.Round(dSetAmount / (1 + dVatRate));
                        view.SetRowCellValue(e.RowHandle, "ConDetVatAmount", dVatAmount);

                        dInsRate = view.GetRowCellValue(e.RowHandle, "ConDetInsRate") == null
                            || view.GetRowCellValue(e.RowHandle, "ConDetInsRate") == DBNull.Value ? 0 :
                                        Convert.ToDecimal(view.GetRowCellValue(e.RowHandle, "ConDetInsRate"));
                        dInsAmount = Math.Round(dInsRate * dVatAmount);
                        view.SetRowCellValue(e.RowHandle, "ConDetInsAmount", dInsAmount);
                    }
                    break;

                case "ConDetVatRate":
                    if (e.Value != null && e.Value != DBNull.Value)
                    {
                        dVatRate = Convert.ToDecimal(e.Value);
                        dSetAmount = view.GetRowCellValue(e.RowHandle, "ConDetSetAmount") == null
                            || view.GetRowCellValue(e.RowHandle, "ConDetSetAmount") == DBNull.Value ? 0 :
                                        Convert.ToDecimal(view.GetRowCellValue(e.RowHandle, "ConDetSetAmount"));
                        dVatAmount = Math.Round(dSetAmount / (1 + dVatRate));
                        view.SetRowCellValue(e.RowHandle, "ConDetVatAmount", dVatAmount);

                        
                    }
                    break;

                case "ConDetInsRate":
                    dInsRate = Convert.ToDecimal(e.Value);
                    dVatAmount = view.GetRowCellValue(e.RowHandle, "ConDetVatAmount") == null
                            || view.GetRowCellValue(e.RowHandle, "ConDetVatAmount") == DBNull.Value ? 0 :
                                        Convert.ToDecimal(view.GetRowCellValue(e.RowHandle, "ConDetVatAmount"));

                    dInsAmount = Math.Round(dInsRate * dVatAmount);
                    view.SetRowCellValue(e.RowHandle, "ConDetInsAmount", dInsAmount);
                    break;
                case "ConDetInsAmount":
                    dInsAmount = Convert.ToDecimal(e.Value);
                    dVatAmount = view.GetRowCellValue(e.RowHandle, "ConDetVatAmount") == null
                            || view.GetRowCellValue(e.RowHandle, "ConDetVatAmount") == DBNull.Value ? 0 :
                                        Convert.ToDecimal(view.GetRowCellValue(e.RowHandle, "ConDetVatAmount"));

                    dInsAfterAmount = Math.Round(dVatAmount - dInsAmount);
                    view.SetRowCellValue(e.RowHandle, "ConDetInsAfterAmount", dInsAfterAmount);
                    break;
                case "ConDetExcRate":
                    dInsRate = Convert.ToDecimal(e.Value);
                    dInsAfterAmount = view.GetRowCellValue(e.RowHandle, "ConDetInsAfterAmount") == null
                            || view.GetRowCellValue(e.RowHandle, "ConDetInsAfterAmount") == DBNull.Value ? 0 :
                                        Convert.ToDecimal(view.GetRowCellValue(e.RowHandle, "ConDetInsAfterAmount"));

                    dInsAmount = Math.Round(dInsRate * dInsAfterAmount);
                    view.SetRowCellValue(e.RowHandle, "ConDetExcAmount", dInsAmount);
                    break;
                case "ConDetTransAmount":
                    dTranAmount = Convert.ToDecimal(e.Value);
                    dInsAfterAmount = view.GetRowCellValue(e.RowHandle, "ConDetInsAfterAmount") == null
                            || view.GetRowCellValue(e.RowHandle, "ConDetInsAfterAmount") == DBNull.Value ? 0 :
                                        Convert.ToDecimal(view.GetRowCellValue(e.RowHandle, "ConDetInsAfterAmount"));
                    dBalanceAmount = Math.Round(dInsAfterAmount - dTranAmount);
                    view.SetRowCellValue(e.RowHandle, "ConDetVccAmount", dBalanceAmount);
                    break;
                

            }
        }

        #endregion

        #region "TextEdit Event"
        private void txtConNo2_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (e.Button.Kind == ButtonPredefines.Ellipsis)
            {
                var frm = new FrmContractFind
                {
                    AsSysBillStyleId = ClsVariable.AsSysBillStyleId,
                    AsSysMyCoYearId = ClsVariable.AsSysMyCoYearId,
                    AsPerPersonId = ClsVariable.EmployeeId,
                    FormNo = this.FormNo,
                    FormSysBillStyleIdExport = FormSysBillStyleIdExport,
                    FormXtraLayoutTemplate = FormXtraLayoutTemplate,
                    FormXtraGridLayoutTemplate = FormXtraGridLayoutTemplate,
                    FormReportLayoutTemplate = FormReportLayoutTemplate,
                    FormDetailVatGridLayout = this.FormDetailVatGridLayout,
                    VoucherCate = this.VoucherCate,
                    IsPrintAfterSave = this.FormIsPrintAfterSave,
                    FormAccountDefault = this.FormAccountDefault,
                    FormIsNotValidate = this.FormIsNotValidate,
                    IsFind=true,
                    WindowState = FormWindowState.Maximized
                };
                frm.Closed += FrmLookupOnClosed;
                frm.ShowDialog();
                frm.Focus();
            }
            if (e.Button.Kind == ButtonPredefines.Delete)
            {
                txtConNo2.Tag = null;
                txtConNo2.EditValue = null;
                txtConName2.EditValue = null;
            }
        }

        private void FrmLookupOnClosed(object sender, EventArgs eventArgs)
        {
            var frmContractFind = sender as FrmContractFind;
            if (frmContractFind != null && frmContractFind.ConId>0)
            {
                txtConNo2.Tag = frmContractFind.ConId;
                txtConNo2.EditValue = frmContractFind.ConNo;
                txtConName2.EditValue = frmContractFind.ConName;
            }
        }
        #endregion



    }
}
